package cc.linker.steplink.crm.controller;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.oss.OssService;
import cc.linker.steplink.crm.merchant.dao.PersonnelDao;
import cc.linker.steplink.crm.merchant.service.QrcodeService;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchanth5.controller.WxShareController;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 重定向
 **/
@Slf4j
@Controller
@RequestMapping("/redirect")
public class RedirectController {


    @Autowired
    private HttpService httpService;

    @Autowired
    private OssService ossService;

    @Autowired
    private QrcodeService qrcodeService;

    @Autowired
    private PurchaseProcessDao purchaseProcessDao;

    @Autowired
    private MerchantInfoService merchantInfoService;


    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private PersonnelDao personnelDao;

    @Autowired
    WxShareController wxShareController;

    @Value("${system.scrm.wxpushurl}")
    private String wxpushurl;

    @GetMapping("/emailReadRedirect/{email}")
    public String redirectSendApi(HttpServletRequest request,
                                               @PathVariable(name = "email") String eventParam) throws Exception {


        LOGGER.info("-----页面重定向 当前收件人事件参数为：" + eventParam);
        // 进行参数获取
        String[] split = eventParam.split(Constants.WXQrCodeMail.ORG_NOTICE);
        LOGGER.info("split:"+split.length);
        if (ArrayUtils.getLength(split) != 2) {
            throw new GlobalException(new ResponseException(400, "邮箱绑定二维码参数不合法"));
        }
        // 取出组装的参数 （生成规则在发邮件那边）
        String email = split[0].replace(Constants.WXQrCodeMail.MAIL_PREFIX, "");
        String[] orgIdAndTaskId = split[1].split(Constants.WXQrCodeMail.TASK_ID_NOTICE);
        String orgId = orgIdAndTaskId[0];
        String taskId = orgIdAndTaskId[1];

        LOGGER.info("orgId:"+orgId);
        LOGGER.info("taskId:"+taskId);
        LOGGER.info("-----二维码参数email：" + email + " orgId:" + orgId + " taskId:" + taskId);

        // 根据taskI和email 更改相关邮件任务状态为已读状态
        Map<String, Object> map = new HashMap<>();
        map.put("emailStatus", 2);
        map.put("email", email);
        map.put("readStatus", 1);
        map.put("readTime", new Date());
        map.put("taskId", taskId);
        personnelDao.updateEmailStatus(map);

        //添加到日志之中
        int pidByEmailAndTaskId = personnelDao.getPidByEmailAndTaskId(map);
        map.put("pid", pidByEmailAndTaskId);
        map.put("readType",Constants.PreciseLogReadType.EMAIL_TYPE);
        personnelDao.addReadLog(map);

        //todo 不生成二维码
        if ("isNull".equals(orgId)) {
            LOGGER.info("orgId  = isNull 不生成二维码 ");
            return  "redirect:空页面";
        }

        // 获取机构ID：orgId，生成带有机构参数的二维码图片
        String qrcodeUrl = showQrcodeImage(orgId, email, eventParam);

        return "redirect:" + qrcodeUrl;
    }

    // 生成带有机构参数的二维码图片
    public String showQrcodeImage(String orgId, String email, String eventParam) throws Exception {
        // TODO 当前有效时间不正确
        String qrcodeUrl = "";
        Map<String, Object> paramWx = new HashMap<>();

        //根据机构获取绑定公众号的唯一token
        String tokenByOrgId = purchaseProcessDao.getTokenByOrgId(orgId);
        if (StringUtils.isEmpty(tokenByOrgId)) {
            throw new GlobalException(new ResponseException(400, "当前机构不存在"));
        }
        paramWx.put("token", tokenByOrgId);
        //生成带邮件号参数的二维码
        paramWx.put("val", eventParam);

        // 生成临时二维码
        paramWx.put("seconds", 30 * 24 * 60 * 60);
        paramWx.put("action", "getStrQrcode");
        String result = httpService.doPost(wxpushurl, JSON.toJSONString(paramWx));
        Map ret = (Map) JSON.parse(result);
        if (200 == (Integer) ret.get("errcode")) {
            Map tmpMap = (Map) ret.get("data");
            qrcodeUrl = ossService.uploadFileToOssByUrl(tmpMap.get("qrcodeurl").toString());
        } else {
            throw GlobalException.build("保存失败");
        }
        return qrcodeUrl;
    }


}
